import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: ['admin']
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles || ['admin']
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password
      }).then(response => {
        const { data } = response

        console.log('登录响应:', response)

        // 根据实际接口返回结构调整
        const token = data.token
        const userInfoData = data.userInfo || data

        // 存储 token
        commit('SET_TOKEN', token)
        setToken(token)

        // 存储用户基本信息
        if (userInfoData) {
          const { name = '', avatar = '' } = userInfoData

          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          // 设置默认角色
          commit('SET_ROLES', ['admin'])
        } else {
          // 如果没有用户信息，设置默认值
          commit('SET_NAME', username)
          commit('SET_ROLES', ['admin'])
        }

        // 返回用户信息
        resolve(userInfoData || { name: username })
      }).catch(error => {
        console.error('登录失败:', error)
        reject(error)
      })
    })
  },

  // 简化的 getInfo，只返回基本用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve) => {
      // 这里可以根据需要从本地存储或其他地方获取用户信息
      // 目前只返回已有的基本信息
      const userInfo = {
        name: state.name,
        avatar: state.avatar,
        roles: state.roles
      }
      resolve(userInfo)
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      const logoutPromise = state.token
        ? logout(state.token)
        : Promise.resolve()

      logoutPromise.then(() => {
        commit('RESET_STATE')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        commit('RESET_STATE')
        removeToken()
        console.error('退出登录API调用失败:', error)
        resolve()
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('RESET_STATE')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
